// FWindow.cpp (c) 2011 JV Software
//

#include "FWin32System_Local.h"

/*
=================
DefaultWndProc
=================
*/
LRESULT CALLBACK DefaultWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    PAINTSTRUCT ps;
    HDC hdc;

    switch( message )
    {
        case WM_PAINT:
            hdc = BeginPaint( hWnd, &ps );
            EndPaint( hWnd, &ps );
            break;

        case WM_DESTROY:
            PostQuitMessage( 0 );
            break;

        default:
            return DefWindowProc( hWnd, message, wParam, lParam );
    }

    return 0;
}

/*
================
FWin32Window::Init
================
*/
void FWin32Window::Init( void *hinst, FString title, FString classname, int width, int height ) {
	 // Register class
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof( WNDCLASSEX );
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = DefaultWndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = (HINSTANCE)hinst;
    wcex.hIcon = LoadIcon( (HINSTANCE)hinst, ( LPCTSTR )IDI_APPLICATION );
    wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = classname.c_str();
    wcex.hIconSm = LoadIcon( wcex.hInstance, ( LPCTSTR )IDI_APPLICATION );
	if( !RegisterClassEx( &wcex ) ) {
		win32Local.FatalError( TEXT("RegisterClassEx: Failed"));
		return;
	}

    // Create window
    RECT rc = { 0, 0, width, height };
    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
    hwnd = CreateWindow( classname.c_str(), title.c_str(), WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, (HINSTANCE)hinst,
                           NULL );
	if( !hwnd ) {
		win32Local.FatalError( TEXT("CreateWindow: Failed"));
		return;
	}

	_width = width;
	_height = height;
}
/*
================
FWin32Window::Destroy
================
*/
void FWin32Window::Destroy( void ) {
	Hide();
}

/*
================
FWin32Window::Show
================
*/
void FWin32Window::Show( void ) {
	if(!hwnd) {
		win32Local.FatalError( TEXT( "FWin32Window::Show: Window isn't valid" ));
		return;
	}

	ShowWindow( hwnd, SW_SHOW );
}

/*
================
FWin32Window::Hide
================
*/
void FWin32Window::Hide( void ) {
	if(!hwnd) {
		win32Local.FatalError( TEXT( "FWin32Window::Hide: Window isn't valid"));
		return;
	}

	ShowWindow( hwnd, SW_HIDE );
}